from django.core.management.base import BaseCommand

from image.models import VmXmlTemplate
from pcservers.models import ComputeArchitecture


def add_vdisk_xml(noarch):
    xml = """
<disk type='network' device='disk'>
  <driver name='qemu' cache='writethrough' discard='ignore'/>
  <auth username='{auth_user}'>
    <secret type='ceph' uuid='{auth_uuid}'/>
  </auth>
  <source protocol='rbd' name='{pool}/{name}'>
  {hosts_xml}
  </source>
    <target dev='{dev}' bus='{bus}'/>   
</disk>
    """

    VmXmlTemplate.objects.create(name='vdisk-xml', xml_type=VmXmlTemplate.XMLConfigType.VDISK_XML.value, xml=xml,
                                 architecture=noarch)


def add_pcie_xml(noarch):
    xml = """
<hostdev mode='%(mode)s' type='%(type)s' managed='yes'>
    <source>
        <address domain='0x%(domain)s' bus='0x%(bus)s' slot='0x%(slot)s' function='0x%(function)s'/>
    </source>
</hostdev>
    """

    VmXmlTemplate.objects.create(name='pcie-xml', xml_type=VmXmlTemplate.XMLConfigType.PCIE_XML.value, xml=xml,
                                 architecture=noarch)


def add_device_xml(noarch):
    xml = """
<disk type='block' device='disk'>
  <driver name='qemu' type='raw' cache='none' io='native' discard='unmap'/>
  <source dev='{dev_drive}'/>
  <target dev='{dev}' bus='{bus}'/>
</disk>
    """

    VmXmlTemplate.objects.create(name='device-xml', xml_type=VmXmlTemplate.XMLConfigType.LOCAL_DEVICE_XML.value,
                                 xml=xml,
                                 architecture=noarch)


def add_noarch_xml(noarch):
    xmls = VmXmlTemplate.objects.all()

    if not xmls:
        add_pcie_xml(noarch)
        add_device_xml(noarch)
        add_vdisk_xml(noarch)

    vdisk_xml = VmXmlTemplate.objects.filter(xml_type=VmXmlTemplate.XMLConfigType.VDISK_XML.value).first()

    if not vdisk_xml:
        add_vdisk_xml(noarch)

    pcie_xml = VmXmlTemplate.objects.filter(xml_type=VmXmlTemplate.XMLConfigType.PCIE_XML.value).first()

    if not pcie_xml:
        add_pcie_xml(noarch)

    device_xml = VmXmlTemplate.objects.filter(xml_type=VmXmlTemplate.XMLConfigType.LOCAL_DEVICE_XML.value).first()

    if not device_xml:
        add_device_xml(noarch)


class Command(BaseCommand):
    '''
    检测/添加全局配置参数
    '''

    help = """ 
            添加 云硬盘、本地设备、pcie xml 信息 
            python3 manage.py add_noach_xml  
           """

    def handle(self, *args, **options):
        print(options)

        noarch = ComputeArchitecture.objects.filter(compute_architecture=ComputeArchitecture.ARCHITECTURE_NOARCH).first()

        try:
            add_noarch_xml(noarch)
        except Exception as e:
            self.stdout.write(self.style.ERROR(
                f"error add noarch xml:{str(e)}"))

            return

        self.stdout.write(
            self.style.SUCCESS(
                'Successfully add noarch xml.'
            )
        )
